package com.lh.exception;

import cn.hutool.core.util.StrUtil;
import com.lh.base.ResResult;
import com.lh.base.ResResultCode;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.UnauthorizedException;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.ArrayList;
import java.util.List;

/**
 * 全局异常处理
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 捕获请求参数异常
     */
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(BadRequestException.class)
    public ResResult handlerBadRequestHandler(BadRequestException e) {
        return new ResResult(ResResultCode.BAD_REQUEST.getStatus(), e.getMessage());
    }

    /**
     * 捕获请求参数异常@Valid校验参数方式
     */
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResResult handlerBadRequestException(MethodArgumentNotValidException e) {
        BindingResult bindingResult = e.getBindingResult();
        List<String> errors = new ArrayList<>();
        for (FieldError fieldError : bindingResult.getFieldErrors()) {
            errors.add(fieldError.getField() + fieldError.getDefaultMessage());
        }
        return new ResResult(ResResultCode.BAD_REQUEST.getStatus(), StrUtil.join("|", errors));
    }

    /**
     * 业务异常 统一捕获返回500
     */
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ExceptionHandler(BizException.class)
    public ResResult handlerBizErrorException(BizException e) {
        if (StrUtil.isNotEmpty(e.getMessage())) {
            e.getResResultCode().setMessage(e.getMessage());
        }
        return ResResult.failure(e.getResResultCode());
    }

    /**
     * 功能异常统一捕获返回
     */
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ExceptionHandler(Exception.class)
    public ResResult handlerException(Exception e) {
        log.error("server error ={}", e.getMessage());
        return ResResult.failure();
    }

    /**
     * 功能异常：异常统一返回 统一返回500状态
     */
    @ResponseStatus(HttpStatus.FORBIDDEN)
    @ExceptionHandler(UnauthorizedException.class)
    public ResResult handlerUnauthorizedException(Exception e) {
        log.error("权限异常：{}", e.getMessage());
        return ResResult.failure(ResResultCode.FORBIDDEN);
    }

}
